<!-- 指标影响矩阵 配置页 -->
<template>
  <div class="equip-wrap-common">
    <div class="equip-table-btn" style="margin-top: 12px">
      <px-button v-has="'INDICATOR_MATRIX_CONFIG_ADD'" type="primary" @click="addBtn">新增</px-button>
    </div>
    <px-table :data="tableData" class="equip-table" height="calc(100vh - 210px)" border :span-method="tableSpanMethod">
      <template #empty>
        <px-empty />
      </template>
      <px-table-column prop="seq" label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ Math.floor($index / 2) + 1 }}
        </template>
      </px-table-column>
      <px-table-column prop="indicatorName" label="中心指标" min-width="120" />
      <px-table-column prop="indicatorType" label="指标类型" min-width="120">
        <template #default="scope">
          {{ scope.row.indicatorType == "1" ? "影响指标" : "关注指标" }}
        </template>
      </px-table-column>
      <template v-for="(item, index) in relatedList" :key="index">
        <px-table-column prop="relatedCollectionList" :label="item.labelName" min-width="120">
          <template #default="scope">
            <px-tooltip
              v-for="(tag, index) in getInicatorName(scope.row.relatedCollectionList, item.classCode, scope.row.indicatorType)"
              :key="index"
              placement="top"
              :disabled="!tag.isOverflow"
              :content="tag.indicatorName"
            >
              <px-tag
                class="mx-1 t-tag"
                style="margin-bottom: 8px"
                @mouseover="tableTagCheckOverflow($event, scope.row.relatedCollectionList, item.classCode, scope.row.indicatorType, index)"
                @mouseleave="tag.isOverflow = false"
              >
                {{ tag.indicatorName }}
              </px-tag>
            </px-tooltip>
            <!-- <div>{{ getInicatorName(scope.row.relatedCollectionList, item.classCode, scope.row.indicatorType) }}</div> -->
          </template>
        </px-table-column>
        <!-- <px-table-column prop="machineType" label="类型" min-width="120">
          <template #default="scope">
            <div>{{ getInicatorType(scope.row.relatedCollectionList, item.classCode) }}</div>
          </template>
        </px-table-column> -->
      </template>
      <px-table-column prop="operation" label="操作" width="96" fixed="right" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="'INDICATOR_MATRIX_CONFIG_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'INDICATOR_MATRIX_CONFIG_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <!-- <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="equip-table-pagination"
      :total="total"
      @pagination="queryTable"
    /> -->
    <px-dialog v-model="dialogVisible" :title="dialogType == 'add' ? '新增' : '编辑'" width="900" @close="closeDialog" @open="fixDialogPosition">
      <px-form ref="formRef" :model="editFormParams" label-width="120px" label-position="right" :rules="editRules">
        <px-row>
          <px-col :span="20">
            <px-form-item label="中心指标" required>
              <px-radio-group v-model="editFormParams.isNew" @change="indicatorTypeChange">
                <px-radio label="1" size="large">自定义</px-radio>
                <px-radio label="0" size="large"
                  >指标库 &nbsp;<px-button
                    v-if="editFormParams.isNew == 0"
                    size="small"
                    type="primary"
                    plain
                    @click="openSelectIndicator('center', '')"
                    >选择</px-button
                  ></px-radio
                >
              </px-radio-group>
            </px-form-item>
            <px-form-item v-if="editFormParams.isNew == 1" prop="indicatorName">
              <px-input v-model="editFormParams.indicatorName" style="width: 350px" type="text" placeholder="请输入自定义指标" />
              <px-select v-model="editFormParams.classCode" style="width: 120px; margin-left: 10px">
                <px-option v-for="item in relatedList" :key="item.classCode" :label="item.className" :value="item.classCode" />
              </px-select>
            </px-form-item>
            <px-form-item v-if="editFormParams.isNew == 0">
              <px-tooltip placement="top" :disabled="!editFormParams.isOverflow" :content="editFormParams.indicatorName">
                <px-tag
                  v-if="editFormParams.indicatorName || editFormParams.indicatorPath"
                  class="mx-1"
                  closable
                  @close="deleteIndicator('center', '', '')"
                  @mouseover="checkOverflow($event, editFormParams)"
                  @mouseleave="editFormParams.isOverflow = false"
                >
                  {{ editFormParams.indicatorName }}
                </px-tag>
              </px-tooltip>
            </px-form-item>
          </px-col>
        </px-row>
        <px-row v-for="(item, index) in editFormParams.relatedCollectionList" :key="item.labelName" class="item-block">
          <px-col :span="20">
            <px-form-item :label="item.labelName" :prop="'relatedCollectionList.' + index + '.isNew'">
              <px-radio-group v-model="item.isNew" @change="rIndicatorTypeChange(item)">
                <px-radio label="1" size="large">自定义</px-radio>
                <px-radio label="0" size="large">指标库 &nbsp;</px-radio>
              </px-radio-group>
            </px-form-item>

            <px-form-item label="关注指标">
              <div v-if="item.isNew == 0">
                <px-tooltip
                  v-for="indicator in item.relatedIndicatorList_0"
                  :key="indicator.indicatorPath"
                  placement="top"
                  :disabled="!indicator.isOverflow"
                  :content="indicator.indicatorName"
                >
                  <px-tag
                    class="mx-1"
                    closable
                    @close="deleteIndicator(item.classCode, indicator.indicatorPath, '0')"
                    @mouseover="checkOverflow($event, indicator)"
                    @mouseleave="indicator.isOverflow = false"
                  >
                    {{ indicator.indicatorName }}
                  </px-tag>
                </px-tooltip>
                <px-button v-if="item.isNew == 0" size="small" type="primary" plain @click="openSelectIndicator(item.classCode, '0')">选择</px-button>
              </div>
              <div v-if="item.isNew == 1">
                <px-input v-model="item.indicatorName_0" style="width: 350px" type="text" placeholder="请输入自定义指标" />
              </div>
            </px-form-item>
            <px-form-item label="影响指标">
              <div v-if="item.isNew == 0">
                <px-tooltip
                  v-for="indicator in item.relatedIndicatorList_1"
                  :key="indicator.indicatorPath"
                  placement="top"
                  :disabled="!indicator.isOverflow"
                  :content="indicator.indicatorName"
                >
                  <px-tag
                    class="mx-1"
                    closable
                    @close="deleteIndicator(item.classCode, indicator.indicatorPath, '1')"
                    @mouseover="checkOverflow($event, indicator)"
                    @mouseleave="indicator.isOverflow = false"
                  >
                    {{ indicator.indicatorName }}
                  </px-tag>
                </px-tooltip>
                <px-button v-if="item.isNew == 0" size="small" type="primary" plain @click="openSelectIndicator(item.classCode, '1')">选择</px-button>
              </div>
              <div v-if="item.isNew == 1">
                <px-input v-model="item.indicatorName_1" style="width: 350px" type="text" placeholder="请输入自定义指标" />
              </div>
            </px-form-item>
          </px-col>
          <!-- <px-col :span="8">
            <px-form-item label="类型" :prop="'relatedCollectionList.' + index + '.type'">
              <px-select v-model="item.type" clearable>
                <px-option v-for="item in indicatorTypeList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col> -->
        </px-row>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="closeDialog">取消</px-button>
          <px-button v-optimize:debounce="{ event: 'click', fn: () => confirmAction(), timeout: 500 }" type="primary"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>

    <px-dialog v-model="selectDialogVisible" title="选择指标" width="800" @close="closeSelectDialog">
      <px-input v-model="filterParams.name" placeholder="请输入关键字" @input="onQueryChanged" />
      <px-tree-v2
        v-if="selectClassCode == 'center'"
        ref="treeRef"
        check-strictly
        :data="centerIndicatorList"
        :current-node-key="editFormParams.indicatorPath"
        :default-expanded-keys="defualtExpendsKeys"
        node-key="id"
        :expand-on-click-node="false"
        :filter-method="filterMethod"
        :height="208"
      />
      <px-tree-v2
        v-if="selectClassCode != 'center'"
        ref="treeRef"
        check-strictly
        show-checkbox
        multiple
        :data="currentIndicatorList"
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        :expand-on-click-node="false"
        :filter-method="filterMethod"
        :height="208"
      />
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="closeSelectDialog">取消</px-button>
          <px-button type="primary" @click="confirmSelect()"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_RUNMANAGE_RECORD"
});
import {
  queryIndicatorConfigList,
  addIndicatorConfig,
  updateIndicatorConfig,
  deleteIndicatorConfig,
  queryMeasureList
} from "@/api/modules/indicator";
import { querySystemSelect } from "@/api/equip/archive";
import { formatDuration } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs, computed, unref, nextTick } from "vue";
import { useRouterStoreHook } from "@/store/modules/router";

const routerStore = useRouterStoreHook();
onMounted(() => {
  // 先查询指标 后查询table 查询 和 新增按钮
  queryIndicatorList();
});
const relatedList = [
  {
    classCode: "MACHINE",
    labelName: "机械科关联指标",
    className: "机械科"
  },
  {
    classCode: "ELECTRICTITY",
    labelName: "电科关联指标",
    className: "电科"
  },
  {
    classCode: "WATER",
    labelName: "水科关联指标",
    className: "水科"
  },
  {
    classCode: "GAS",
    labelName: "气化科关联指标",
    className: "气化科"
  },
  {
    classCode: "FAB",
    labelName: "机台侧关联指标",
    className: "机台侧"
  }
];
// const defaultProps = {
//   children: "children",
//   label: "name",
//   value: "code"
// };
const state = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  indicatorLoaded: false, // 判断指标是否已经查询
  tableData: [], // 列表数据
  total: 0, // 列表数量
  centerIndicatorList: [], // 中心指标
  machineIndicatorList: [], //机械科指标
  electricityIndicatorList: [], //电科指标
  gasIndicatorList: [], //气化科指标
  waterIndicatorList: [], //水科指标
  fabIndicatorList: [], //机台侧指标
  rowData: {}, // 当前行数据
  dialogVisible: false, // 弹窗显示隐藏
  selectDialogVisible: false, //选择指标弹框
  dialogType: "add", // 弹窗默认新增
  editFormParams: {},
  indicatorTypeList: [
    {
      value: "0",
      name: "关注指标"
    },
    {
      value: "1",
      name: "影响指标"
    }
  ],
  formRef: null,
  treeRef: null,
  filterParams: {
    name: ""
  },
  selectClassCode: "",
  selectType: "",
  defualtExpendsKeys: [],
  defaultCheckedKeys: []
});

const {
  queryParams,
  indicatorLoaded,
  tableData,
  total,
  centerIndicatorList,
  machineIndicatorList,
  electricityIndicatorList,
  gasIndicatorList,
  waterIndicatorList,
  fabIndicatorList,
  editFormParams,
  rowData,
  dialogVisible,
  selectDialogVisible,
  dialogType,
  indicatorTypeList,
  formRef,
  treeRef,
  filterParams,
  selectClassCode,
  selectType,
  defualtExpendsKeys,
  defaultCheckedKeys
} = toRefs(state);
const checkIndicatorName = (rule, value, callback) => {
  if (editFormParams.value.isNew == 1 && !value) {
    return callback(new Error("请输入"));
  } else {
    callback();
  }
};
const checkIndicatorCode = (rule, value, callback) => {
  if (editFormParams.value.isNew == 0 && !value) {
    return callback(new Error("请选择"));
  } else {
    callback();
  }
};
const checkRelatedCollection = (rule, value, callback) => {
  if (value.every(item => !item.indicatorCode || !item.indicatorName)) {
    callback(new Error("请维护至少一项关联指标"));
  } else {
    callback();
  }
};
const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};
const checkIndicatorType = (rule, value, callback) => {
  const index = parseInt(rule.field.split(".")[1]); //当前索引
  if (
    (editFormParams.value.relatedCollectionList[index].indicatorPath && editFormParams.value.relatedCollectionList[index].indicatorCode.length) ||
    editFormParams.value.relatedCollectionList[index].indicatorName
  ) {
    if (valueIsEmpty(value)) {
      callback(new Error("请选择"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const editRules = computed(() => ({
  indicatorName: [{ validator: checkIndicatorName, message: "请输入", trigger: "blur" }],
  indicatorPath: [{ validator: checkIndicatorCode, message: "请选择", trigger: "change" }]
  // relatedCollection: [{ validator: checkRelatedCollection, message: '请维护至少一项关联指标', trigger: 'blur' }],
}));
// 指标数据转成tree-select数据的格式
const convertData = node => {
  node.id = node.measureCode;
  node.label = node.measureName;
  delete node.measureCode;
  delete node.measureName;
  if (node.children) {
    node.children.forEach(child => {
      convertData(child);
    });
  }
};
// 指标下拉
const queryIndicatorList = async () => {
  queryMeasureList({ className: "" }).then(res => {
    console.log(res);
    centerIndicatorList.value = res || [];
    centerIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryMeasureList({ className: "ELECTRICTITY" }).then(res => {
    console.log(res);
    electricityIndicatorList.value = res || [];
    electricityIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryMeasureList({ className: "MACHINE" }).then(res => {
    console.log(res);
    machineIndicatorList.value = res || [];
    machineIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryMeasureList({ className: "GAS" }).then(res => {
    console.log(res);
    gasIndicatorList.value = res || [];
    gasIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryMeasureList({ className: "WATER" }).then(res => {
    console.log(res);
    waterIndicatorList.value = res || [];
    waterIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryMeasureList({ className: "FAB" }).then(res => {
    console.log(res);
    fabIndicatorList.value = res || [];
    fabIndicatorList.value.forEach(item => {
      convertData(item);
    });
  });
  queryTable();
};

// 查询列表
const queryTable = async () => {
  const res = await queryIndicatorConfigList({ classType: "0" });
  // 组装数据
  let tmp = [];
  if (res && res.length) {
    res.forEach(v => {
      tmp.push({
        ...v,
        indicatorType: "0"
      });
      tmp.push({
        ...v,
        indicatorType: "1"
      });
    });
  }
  tableData.value = tmp;
  // total.value = res?.total;
};
const tableSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property == "indicatorName" || column.property == "operation" || column.property == "seq") {
    if (rowIndex % 2 == 0) {
      //row.isFirst
      return {
        rowspan: 2, // 按照layer合并 row.layerGap
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
const currentIndicatorList = computed(() => {
  if (selectClassCode.value == "MACHINE") {
    return machineIndicatorList.value;
  }
  if (selectClassCode.value == "WATER") {
    return waterIndicatorList.value;
  }
  if (selectClassCode.value == "GAS") {
    return gasIndicatorList.value;
  }
  if (selectClassCode.value == "ELECTRICTITY") {
    return electricityIndicatorList.value;
  }
  return [];
});
const getInicatorName = (list, classCode, type) => {
  let n = [];
  let t = list.filter(v => v.classCode == classCode);
  if (t && t.length) {
    if (t[0].relatedIndicatorList && t[0].relatedIndicatorList.length) {
      let list = t[0].relatedIndicatorList.filter(ri => ri.type == type);
      list.forEach(item => {
        n.push({ indicatorName: item.indicatorName, isOverflow: item.isOverflow });
      });
      // t[0].relatedIndicatorList.forEach(item => {
      //   n.push(item.indicatorName);
      // });
    }
  }
  return n;
  // return n.join(",");
};
const getInicatorType = (list, classCode) => {
  let t = list.filter(v => v.classCode == classCode);
  let type = t[0]?.type;

  return type == "1" ? "影响指标" : type == "0" ? "关注指标" : "";
};
// 关闭弹窗
const closeDialog = () => {
  formRef.value?.clearValidate();
  dialogVisible.value = false;
};

const openSelectIndicator = (classCode, type) => {
  console.log(classCode);
  selectClassCode.value = classCode;
  selectType.value = type;
  if (classCode == "center" && editFormParams.value.indicatorPath) {
    let parents = getParents(unref(centerIndicatorList.value), editFormParams.value.indicatorPath);
    let ids = parents.map(v => v.id);
    ids.pop();
    defualtExpendsKeys.value = ids;
    treeRef.value.setExpandedKeys(ids);
  } else {
    editFormParams.value.relatedCollectionList.forEach(v => {
      if (v.classCode == selectClassCode.value) {
        let currentList = v.relatedIndicatorList_0;
        if (type == "1") {
          currentList = v.relatedIndicatorList_1;
        }
        if (currentList && currentList.length) {
          defaultCheckedKeys.value = currentList.map(keys => keys.indicatorPath);
          nextTick(() => {
            treeRef.value?.setCheckedKeys(defaultCheckedKeys.value);
            currentList.forEach(item => {
              let parents = getParents(unref(currentIndicatorList), item.indicatorPath);
              let ids = parents.map(v => v.id);
              ids.pop();
              defualtExpendsKeys.value = ids;
              treeRef.value?.setExpandedKeys(ids);
            });
          });
        } else {
          defaultCheckedKeys.value = [];
          defualtExpendsKeys.value = [];
          treeRef.value?.setCheckedKeys([]);
        }
      }
    });
  }
  selectDialogVisible.value = true;
};
// 关闭弹窗
const closeSelectDialog = () => {
  filterParams.value.name = "";
  selectClassCode.value = "";
  selectDialogVisible.value = false;
};
const indicatorTypeChange = () => {
  editFormParams.value.indicatorName = "";
  editFormParams.value.indicatorPath = "";
  editFormParams.value.systemCode = "";
  editFormParams.value.isIndicator = "";
  // editFormParams.value.indicatorCode = "";
};
const rIndicatorTypeChange = item => {
  editFormParams.value.relatedCollectionList.forEach(v => {
    if (v.classCode == item.classCode) {
      v.indicatorName_0 = "";
      v.indicatorName_1 = "";
      v.relatedIndicatorList = [];
      v.relatedIndicatorList_0 = [];
      v.relatedIndicatorList_1 = [];
    }
  });
  // editFormParams.value.indicatorName = "";
  // editFormParams.value.indicatorPath = "";
  // editFormParams.value.indicatorCode = "";
};
// function getParents(tree, measureCode, parents = []) {
//   for (let i = 0; i < tree.length; i++) {
//     if (tree[i].measureCode === measureCode) {
//       // 找到目标节点，返回路径
//       return [...parents, tree[i]];
//     }
//     if (tree[i].children) {
//       let node = getParents(tree[i].children, measureCode, [...parents, tree[i]]);
//       if (node) {
//         return node;
//       }
//     }
//   }
//   return []; // 如果没有找到父节点，返回空数组
// }
function getParents(tree, id, parents = []) {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id == id) {
      // 找到目标节点，返回路径
      return [...parents, tree[i]];
    }
    if (tree[i].children) {
      let node = getParents(tree[i].children, id, [...parents, tree[i]]);
      if (node.length) {
        return node;
      }
    }
  }
  return []; // 如果没有找到父节点，返回空数组
}
//中心指标树点击
const centerIndicatorClick = data => {
  // 取当前节点的名称，并给indicationPath赋值
  editFormParams.value.indicatorName = data.label;
  editFormParams.value.indicatorPath = data.value;
  if (data.type == "measure") {
    editFormParams.value.isIndicator = "1";
    // parents为该指标的路径数组
    let parents = getParents(centerIndicatorList.value, data.value);
    let p = parents.filter(v => v.type == "systemModel");
    if (p && p.length) {
      editFormParams.value.systemCode = p[0].measureCode;
    } else {
      editFormParams.value.systemCode = "";
    }
  } else {
    editFormParams.value.isIndicator = "0";
    editFormParams.value.systemCode = "";
  }
};
// const relatedCollectionChange = (item,data,checked,indeterminate) => {
//   debugger
// }
const relatedCollectionCheck = (item, data, checkedData) => {
  let checkedCodes = [],
    checkedNames = [];
  let tmpList = [];
  checkedData.checkedNodes.forEach(v => {
    let systemCode = "",
      indicatorPath = v.value,
      indicatorName = v.label,
      isIndicator = "";
    if (v.type == "measure") {
      isIndicator = "1";
      // parents为该指标的路径数组
      let parents = getParents(item.indicatorList, v.value);
      let p = parents.filter(n => n.type == "systemModel");
      if (p && p.length) {
        systemCode = p[0].measureCode;
      } else {
        systemCode = "";
      }
    } else {
      isIndicator = "0";
      systemCode = "";
    }
    tmpList.push({
      systemCode,
      indicatorPath,
      indicatorName,
      isIndicator
    });
    checkedCodes.push(v.value);
    checkedNames.push(v.label);
  });
  editFormParams.value.relatedCollectionList.forEach(v => {
    if (v.classCode == item.classCode) {
      v.indicatorName = checkedNames.toString();
      v.indicatorCode = checkedCodes;
      v.relatedIndicatorList = tmpList;
    }
  });
};
const getInicatorList = classCode => {
  if (classCode == "MACHINE") {
    return machineIndicatorList.value;
  }
  if (classCode == "ELECTRICTITY") {
    return electricityIndicatorList.value;
  }
  if (classCode == "WATER") {
    return waterIndicatorList.value;
  }
  if (classCode == "GAS") {
    return gasIndicatorList.value;
  }
  if (classCode == "FAB") {
    return fabIndicatorList.value;
  }
};
const getInicatorInfo = (classCode, list) => {
  let t = list.filter(v => v.classCode == classCode);
  let codes = [],
    names = [],
    type = "",
    isNew = "0",
    id = "",
    relatedIndicatorList = [],
    relatedIndicatorList_0 = [],
    relatedIndicatorList_1 = [];
  if (t && t.length) {
    codes = t[0].relatedIndicatorList.map(item => item.indicatorPath);
    names = t[0].relatedIndicatorList.map(item => item.indicatorName);
    type = !valueIsEmpty(t[0].type) ? t[0].type : "";
    isNew = !valueIsEmpty(t[0].isNew) ? t[0].isNew : "0";
    id = t[0].id;
    relatedIndicatorList = t[0].relatedIndicatorList;
    relatedIndicatorList_0 = relatedIndicatorList.filter(v => v.type == "0");
    relatedIndicatorList_1 = relatedIndicatorList.filter(v => v.type == "1");
  }
  return {
    codes,
    names: names.toString(),
    id,
    type,
    isNew,
    relatedIndicatorList,
    relatedIndicatorList_0,
    relatedIndicatorList_1
  };
};
const getRelatedCollection = row => {
  let tmpList = [];
  relatedList.forEach(v => {
    let cn = getInicatorInfo(v.classCode, row.relatedCollectionList || []);
    tmpList.push({
      ...v,
      id: cn.id || "",
      isNew: cn.isNew,
      indicatorList: getInicatorList(v.classCode),
      indicatorName_0: cn.isNew == "1" ? cn.relatedIndicatorList.filter(v => v.type == "0")?.[0].indicatorName : "",
      indicatorName_1: cn.isNew == "1" ? cn.relatedIndicatorList.filter(v => v.type == "1")?.[0].indicatorName : "",
      relatedIndicatorList: cn.relatedIndicatorList || [],
      relatedIndicatorList_0: cn.relatedIndicatorList.filter(v => v.type == "0"),
      relatedIndicatorList_1: cn.relatedIndicatorList.filter(v => v.type == "1")
      // indicatorCode: cn.codes,
      // indicatorName: cn.names,
      // type: cn.type
    });
  });
  return tmpList;
};
// 新增-显示弹窗
const addBtn = () => {
  dialogType.value = "add";
  editFormParams.value = {
    id: "",
    indicatorPath: "",
    indicatorName: "",
    // indicatorCode: "",
    isNew: "0",
    classCode: routerStore.getSubject === "ALL" ? "ELECTRICTITY" : routerStore.getSubject,
    relatedCollectionList: getRelatedCollection({})
  };
  dialogVisible.value = true;
};
// 编辑-显示弹窗
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  rowData.value = row;
  editFormParams.value = {
    id: row.id,
    systemCode: row.systemCode,
    isIndicator: row.isIndicator,
    indicatorPath: row.indicatorPath, //拼接 or 还是先只存选中的？
    indicatorName: row.indicatorName, //拼接 or 还是先只存选中的?
    isNew: valueIsEmpty(row.isNew) ? "0" : row.isNew,
    classCode: row.classCode,
    level: row.level,
    relatedCollectionList: getRelatedCollection(row)
  };
  dialogVisible.value = true;
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm("要删除当前配置吗？", "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteIndicatorConfig({ id: row.id });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
const deleteIndicator = (classCode, path, type) => {
  if (classCode == "center") {
    editFormParams.value.indicatorPath = "";
    editFormParams.value.indicatorName = "";
  } else {
    editFormParams.value.relatedCollectionList.forEach(v => {
      if (v.classCode == classCode) {
        if (type == "0") {
          const index = v.relatedIndicatorList_0.findIndex(element => element.indicatorPath === path);
          if (index !== -1) {
            v.relatedIndicatorList_0.splice(index, 1);
          }
        }
        if (type == "1") {
          const index = v.relatedIndicatorList_1.findIndex(element => element.indicatorPath === path);
          if (index !== -1) {
            v.relatedIndicatorList_1.splice(index, 1);
          }
        }
      }
    });
  }
  console.log(type);
};
const confirmSelect = () => {
  if (selectClassCode.value == "center") {
    let node = treeRef.value?.getCurrentNode();
    if (!node?.id) {
      PxMessage.error("请选择指标！");
      return;
    }
    editFormParams.value.indicatorPath = node.id;
    editFormParams.value.indicatorName = node.label;
    editFormParams.value.level = node.type;
    // parents为该指标的路径数组
    let parents = getParents(unref(centerIndicatorList), node.id);
    let p = parents.filter(v => v.type == "systemModel");
    let ccode = parents.filter(v => v.type == "className");

    if (node.type == "measure") {
      editFormParams.value.isIndicator = "1";
      if (p && p.length) {
        editFormParams.value.systemCode = p[0].id;
      } else {
        editFormParams.value.systemCode = "";
      }
      if (ccode && ccode.length) {
        editFormParams.value.classCode = ccode[0].id;
      }
    } else {
      editFormParams.value.isIndicator = "0";
      editFormParams.value.systemCode = "";
      if (node.type != "className") {
        if (ccode && ccode.length) {
          editFormParams.value.classCode = ccode[0].id;
        }
      } else {
        editFormParams.value.classCode = node.id;
      }
    }
  } else {
    let nodes = treeRef.value?.getCheckedNodes();
    if (!nodes?.length) {
      PxMessage.error("请选择指标！");
      return;
    }
    let tmpList = [];
    nodes.forEach(v => {
      let systemCode = "",
        indicatorPath = v.id,
        indicatorName = v.label,
        isIndicator = "";
      if (v.type == "measure") {
        isIndicator = "1";
        // parents为该指标的路径数组
        let parents = getParents(unref(currentIndicatorList), v.id);
        let p = parents.filter(n => n.type == "systemModel");
        if (p && p.length) {
          systemCode = p[0].id;
        } else {
          systemCode = "";
        }
      } else {
        isIndicator = "0";
        systemCode = "";
      }
      tmpList.push({
        systemCode,
        indicatorPath,
        indicatorName,
        isIndicator,
        type: selectType.value,
        level: v.type
      });
    });
    editFormParams.value.relatedCollectionList.forEach(v => {
      if (v.classCode == selectClassCode.value) {
        if (selectType.value == "0") {
          v.relatedIndicatorList_0 = tmpList;
        }
        if (selectType.value == "1") {
          v.relatedIndicatorList_1 = tmpList;
        }
      }
    });
  }
  closeSelectDialog();
};
const onQueryChanged = () => {
  treeRef.value?.filter(filterParams.value.name);
};
const filterMethod = (query, node) => {
  return node.label?.includes(query);
};
const confirmAction = () => {
  // 保存指标信息 组装保存参数
  // editFormParams.value 去除多余字段
  formRef.value?.validate(async (valid, fields) => {
    if (valid) {
      if (!editFormParams.value.indicatorName) {
        PxMessage.error("中心指标不能为空");
        return;
      }
      // 至少维护一个关联指标
      let flag_i = true;
      editFormParams.value.relatedCollectionList.forEach(v => {
        if (
          v.isNew != 1 &&
          ((v.relatedIndicatorList_0 && v.relatedIndicatorList_0.length) || (v.relatedIndicatorList_1 && v.relatedIndicatorList_1.length))
        ) {
          flag_i = false;
        }
        if (v.isNew == "1" && (v.indicatorName_0 || v.indicatorName_1)) {
          flag_i = false;
        }
      });
      if (flag_i) {
        PxMessage.error("至少维护一个关联指标");
        return;
      }

      let funName = addIndicatorConfig;
      if (dialogType.value == "edit") {
        funName = updateIndicatorConfig;
      }
      // 组装需要的数据
      let params = {
        id: editFormParams.value.id,
        isNew: editFormParams.value.isNew,
        indicatorPath: editFormParams.value.isNew != 1 ? editFormParams.value.indicatorPath : "",
        indicatorName: editFormParams.value.indicatorName,
        relatedCollectionList: [],
        classType: "0", // 0 四科 1 水科
        isIndicator: editFormParams.value.isIndicator,
        systemCode: editFormParams.value.systemCode,
        classCode: editFormParams.value.classCode,
        level: editFormParams.value.isNew != 1 ? editFormParams.value.level : "custom"
      };
      editFormParams.value.relatedCollectionList.forEach(v => {
        if (v.isNew == "1") {
          if (v.indicatorName_0 || v.indicatorName_1) {
            params.relatedCollectionList.push({
              id: v.id,
              isNew: v.isNew,
              classCode: v.classCode,
              relatedIndicatorList: [
                { indicatorName: v.indicatorName_0, type: "0", level: "custom" },
                { indicatorName: v.indicatorName_1, type: "1", level: "custom" }
              ]
            });
          }
        } else {
          params.relatedCollectionList.push({
            id: v.id,
            isNew: v.isNew,
            classCode: v.classCode,
            relatedIndicatorList: [...v.relatedIndicatorList_0, ...v.relatedIndicatorList_1]
          });
        }
      });
      let res = await funName({ ...params });
      PxMessage.success(dialogType.value == "edit" ? "更新成功" : "保存成功");
      closeDialog();
      queryTable();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const checkOverflow = (event, item) => {
  const element = event.target;
  item.isOverflow = element.children[0].scrollWidth > element.children[0].clientWidth;
};
const tableTagCheckOverflow = (event, list, classCode, type, index) => {
  const element = event.target;
  let isOverflow = element.children[0].scrollWidth > element.children[0].clientWidth;
  let t = list.filter(v => v.classCode == classCode);
  if (t && t.length) {
    if (t[0].relatedIndicatorList && t[0].relatedIndicatorList.length) {
      let tlist = t[0].relatedIndicatorList.filter(ri => ri.type == type);
      tlist[index].isOverflow = isOverflow;
    }
  }
};
const fixDialogPosition = () => {
  // 复位弹框的滚动位置（如果需要）
  const dialogWrap = document.querySelector(".px-overlay-dialog");
  if (dialogWrap) {
    dialogWrap.scrollTop = 0; // 复位弹框内部滚动条（如果有）
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-wrap-common {
  height: calc(100vh - 177px);

  .equip-form {
    margin-bottom: 8px;

    :deep(.px-form-item) {
      width: 20%;
      margin-bottom: 8px;
    }

    :deep(.px-button) {
      margin-top: -8px;
    }
  }
}

.item-block {
  padding-top: 10px;
  margin-bottom: 12px;
  border: 1px dashed #dcdcdc;
}

:deep(.px-tree) {
  border: 1px solid #d5d5d5;
}

:deep(.t-tag) {
  max-width: 100%;
}
</style>
